package blockchain

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"strconv"
	"sync"
	"time"

	"github.com/gorilla/mux"
)

// Message - 生成证书消息体
type Message struct {
	CommonName   string
	Organization string
	PubKeyData   string
}

var mutex = &sync.Mutex{}

// QueryServer - 区块信息查询服务器，比如区块高度信息等
type QueryServer struct {
	ledger *Ledger
}

// Run - 启动查询服务器
func (qs *QueryServer) Run(ledger *Ledger) error {
	qs.ledger = ledger
	mux := qs.makeMuxRouter()
	httpPort := Config.HTTPPort
	log.Println("区块查询服务器正监听端口:", httpPort)
	s := &http.Server{
		Addr:           ":" + string(httpPort),
		Handler:        mux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	if err := s.ListenAndServe(); err != nil {
		return err
	}

	return nil
}

// create handlers
func (qs *QueryServer) makeMuxRouter() http.Handler {
	muxRouter := mux.NewRouter()
	muxRouter.HandleFunc("/get_blockchain_height", qs.handleGetBlockchainHeight).Methods("GET")
	muxRouter.HandleFunc("/get_block", qs.handleGetBlock).Methods("GET")
	muxRouter.HandleFunc("/get_transaction", qs.handleGetTransaction).Methods("GET")
	return muxRouter
}

func (qs *QueryServer) handleGetBlockchainHeight(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	io.WriteString(w, strconv.Itoa(qs.ledger.CurBlock.Header.Index))
}

func (qs *QueryServer) handleGetBlock(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	response, err := json.Marshal(qs.ledger.CurBlock)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("HTTP 500: Internal Server Error"))
		return
	}
	w.WriteHeader(http.StatusCreated)
	w.Write(response)
}

func (qs *QueryServer) handleGetTransaction(w http.ResponseWriter, r *http.Request) {

}
